package com.zjpavt.client.page;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.zjpavt.client.enums.ExtendDeviceEnum;
import com.zjpavt.client.enums.ThreePhase;
import com.zjpavt.client.extenddevice.IVoltageAndCurrentDetection;
import com.zjpavt.client.hal.ExtendDeviceManager;
import com.zjpavt.client.hal.LedScreen;
import com.zjpavt.client.hal.VoltageAndCurrentManager;
import com.zjpavt.client.page.abstractpage.AbstractEditablePage;
import com.zjpavt.client.page.editableunit.EditUnitString;
import com.zjpavt.client.page.intefacepage.MultiPage;
import com.zjpavt.client.page.pageunit.ScreenLine;
import com.zjpavt.client.util.PropertiesUtil;

public class CurrentChannelStatePage  extends AbstractEditablePage implements MultiPage {

    /**
     * 内嵌页面页码 从0开始
     */
    protected int multiPageNum = 0;

    /**
     * 总通道数
     */
    private int mLoopNum=12;

    private static String[] threePhaseArrays = new String[] {"0", "1"};

    private final int rowNumber = 12;//每行显示的通道数量

    private String elecChannelStatus;//通道状态

    private final int pageElecChannelNum=36;//每页最大通道数量

    /**
     * //每页放的通道数最大36
     * @return
     */
    private int getPageElecChannelNum() {
        return pageElecChannelNum*multiPageNum;
    }

    private IVoltageAndCurrentDetection ivacd=null;

    public CurrentChannelStatePage(int pageNum, int mRefreshPeriod) {
        super(pageNum, mRefreshPeriod);
        setMLoopNumElecChannelStatus();
    }

    private void setMLoopNumElecChannelStatus() {
        // 添加设备
        Map<Integer, IVoltageAndCurrentDetection> voltageAndCurrentExtendDeviceMap = ExtendDeviceManager.getInstance().getVoltageAndCurrentExtendDeviceMap();
        if(voltageAndCurrentExtendDeviceMap.keySet().size()>0) {
            Iterator<Map.Entry<Integer,IVoltageAndCurrentDetection>> it = voltageAndCurrentExtendDeviceMap.entrySet().iterator();
            for (; it.hasNext(); ) {
                Map.Entry <Integer,IVoltageAndCurrentDetection> voltageAndCurrentDetection = it.next();
                ivacd = voltageAndCurrentDetection.getValue();
                mLoopNum = ivacd.getLoopNum();
            }
        }
        try {
            if(ivacd == null) {
                elecChannelStatus="000000000000";
            } else if (ivacd.getDeviceType().equals(ExtendDeviceEnum.ELECT)) {
                elecChannelStatus = PropertiesUtil.getPropertiesDefault(ElecConfigPage.ELEC_CHANNEL_IS_TESTING,"000000000000");
                mLoopNum = Integer.valueOf(PropertiesUtil.getPropertiesDefault(ElecConfigPage.ELEC_CHANNEL_NUM,"12"));
            } else {
                elecChannelStatus = PropertiesUtil.getPropertiesDefault(ElecConfigPage.DEFAULT_ELEC_CHANNEL_IS_TESTING,"000000000000");;
            }
        } catch (IOException e) {
            e.printStackTrace();
        };
    }

    @Override
    public void refreshPage() {
        setMLoopNumElecChannelStatus();//取通道口
        List<ScreenLine> result = new ArrayList<>();

        //第一行显示名称
        if(ivacd == null) {
            result.add(new ScreenLine.ScreenLineBuilder().text(ExtendDeviceEnum.CIRCUIT.toString()).pageNum(getPageNum()).build());
        } else if (ivacd.getDeviceType().equals(ExtendDeviceEnum.ELECT)) {
            result.add(new ScreenLine.ScreenLineBuilder().text(ExtendDeviceEnum.ELECT.toString()).pageNum(getPageNum()).build());
        } else {
            result.add(new ScreenLine.ScreenLineBuilder().text(ExtendDeviceEnum.CIRCUIT.toString()).pageNum(getPageNum()).build());
        }
        int pageNum = getPageElecChannelNum();//算出当前页通道数
        for(int i=1; i<LedScreen.SCREEN_HEIGHT; i++) {
            int beginIndex=pageNum;
            if(i==1) {
                beginIndex+=0;
            } else if(i==2) {
                beginIndex+=12;
            } else {
                beginIndex+=24;
            }
            if(mLoopNum-beginIndex>=12) {
                result.add(new ScreenLine.ScreenLineBuilder().text(elecChannelStatus.substring(beginIndex, rowNumber*i+getPageElecChannelNum())).build());
            } else if(mLoopNum-beginIndex<12 && mLoopNum-beginIndex>0) {
                result.add(new ScreenLine.ScreenLineBuilder().text(elecChannelStatus.substring(beginIndex, elecChannelStatus.length())).build());
            } else {
                result.add(new ScreenLine.ScreenLineBuilder().text("").build());
            }
        }
        LedScreen.getInstance().setText(result);
    }

    @Override
    public void onKeySet() {
        if (!super.isInEditMode()) {//当它为不可编辑状态时，刷新编辑与初始化参数
            clearEditUnit();
            initEditUnits();
        }
        super.onKeySet();
    }

    @Override
    public void onKeyEnt() {
        if (super.isInEditMode()) {
            super.onKeyEnt();
        } else {
            change2NextPage();//翻页
        }
    }

    @Override
    public void onKeyDown() {
        if (!super.isInEditMode()) {
            exitPage();
        }
        super.onKeyDown();
    }

    @Override
    public void onKeyUp() {
        if (!super.isInEditMode()) {
            exitPage();
        }
        super.onKeyUp();
    }

    @Override
    public int getPageSize() {
        return mLoopNum%36>0?mLoopNum/36+1:mLoopNum/36;
    }

    @Override
    public int getMultiPageNum() {
        return multiPageNum;
    }

    @Override
    public void change2Page(int pageNum) {
        if (pageNum > getPageNum()) {
            return;
        }
        this.multiPageNum = pageNum;
        refreshPage();
    }

    @Override
    public void change2NextPage() {
        if (multiPageNum == getPageSize() - 1) {
            multiPageNum = 0;
        } else {
            multiPageNum++;
        }
        refreshPage();
    }

    @Override
    public void exitPage() {
        this.multiPageNum = 0;
    }

    @Override
    public void setDefaultVal() {
        //截取出当前页面的字符串
        String elecChannelStatus = this.elecChannelStatus.substring(getPageElecChannelNum(),
                                   this.elecChannelStatus.length()-getPageElecChannelNum()-pageElecChannelNum>0?pageElecChannelNum+getPageElecChannelNum()
                                   :this.elecChannelStatus.length()%36+getPageElecChannelNum());
        //然后循环设置为初始值
        for(int i=0; i<elecChannelStatus.length(); i++) {
            getEditUnit(i).setCurrentVal(Integer.valueOf(elecChannelStatus.substring(i, i+1)));
        }
    }

    @Override
    public void initEditUnits() {
        int mLoopNum = this.elecChannelStatus.length()-getPageElecChannelNum()-pageElecChannelNum>0?pageElecChannelNum:this.elecChannelStatus.length()%36;//每页通道数
        int y=1;//第几行
        int x=1;//第几个
        for(int i=1; i<=mLoopNum; i++) {
            if(x%12==1) {
                x=1;
            }
            if(i<=12) {
                y=2;
            } else if(i>12 && i<=24) {
                y=3;
            } else {
                y=4;
            }
            addEditUnit(new EditUnitString(y, x, x, threePhaseArrays));// VIDEO
            x++;
        }
    }

    @Override
    public void saveVal() {
        String elecChannelStatus = "";//前面字符串
        String strFront =  this.elecChannelStatus.substring(0, getPageElecChannelNum());
        String strAfter = "";//后面字符串
        if(getPageElecChannelNum()+pageElecChannelNum<this.elecChannelStatus.length()) {
            strAfter =  this.elecChannelStatus.substring(getPageElecChannelNum()+pageElecChannelNum, this.elecChannelStatus.length());
        }
        //从数组中获取编辑的个数
        for(int i=0; i<getEditUnitSize(); i++) {
            elecChannelStatus+=getEditUnit(i).getText();
        }
        //拼接多出来的部分
        if(this.multiPageNum==0) {
            elecChannelStatus+=strAfter;
        } else if(this.multiPageNum==1) {
            elecChannelStatus = strFront+elecChannelStatus+strAfter;
        } else {
            elecChannelStatus=strFront+elecChannelStatus;
        }
        try {
            //保存到文件里面
            if (ivacd.getDeviceType().equals(ExtendDeviceEnum.ELECT)) {
                PropertiesUtil.setPropertyOrReplaceDefault(ElecConfigPage.ELEC_CHANNEL_IS_TESTING,elecChannelStatus);
            } else {
                PropertiesUtil.setPropertyOrReplaceDefault(ElecConfigPage.DEFAULT_ELEC_CHANNEL_IS_TESTING,elecChannelStatus);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
